package core;

import javax.microedition.io.file.*;
import java.util.*;
import javax.microedition.io.*;

public class Browser implements Runnable
{
	private Thread thread;
	private BrowserAction listener;
	private int code;
	private String path;
	
	public Browser(BrowserAction a)
	{
		super();
		listener = a;
	}
	
	public void getRoots()
	{
		code = 1;
		thread = new Thread(this);
		thread.start();
	}
	
	public void getFolders(String _path)
	{
		code = 2;
		path = _path;
		thread = new Thread(this);
		thread.start();
	}
	
	public void run() 
	{
		try
		{
			if (code==1)
			{
				Enumeration e = FileSystemRegistry.listRoots();
				Vector roots = new Vector();
				while (e.hasMoreElements()) 
				{
					String rootName = (String)e.nextElement();
					roots.addElement(rootName);
				}
				listener.browserAction(code,roots,null);
			}
			else
			{
				FileConnection fc = (FileConnection)Connector.open(path);
				try
				{
					Enumeration e = fc.list();
					Vector folders = new Vector();
					Vector files = new Vector();
					while (e.hasMoreElements()) 
					{
						String rootName = (String)e.nextElement();
						if (rootName.indexOf("/")!=-1)
						{
							folders.addElement(rootName);
						}
						else
						{
							files.addElement(rootName);
						}
					}
					listener.browserAction(code,folders,files);
				}
				finally
				{
					fc.close();
				}
			}
		}catch(Exception x)
		{
			listener.browserAction(-1,null,null);
		}
	}
	
}
